#include "LambertianMaterial.h"

using namespace OBR;

std::shared_ptr<CudaProgram> LambertianMaterial::program;
CudaBuffer LambertianMaterial::sbt_data_payload;

LambertianMaterial::LambertianMaterial()
    : Material("shaders/Material/LambertianMaterial.cu"), albedo(Spectrum(1.0f))
{
    this->program_desc.callables.entryFunctionNameDC = "__direct_callable__lambertian_material";
    this->program_desc.kind = OPTIX_PROGRAM_GROUP_KIND_CALLABLES;
    this->program_desc.flags = OPTIX_GEOMETRY_FLAG_NONE;
}

LambertianMaterial::~LambertianMaterial()
{
}

void LambertianMaterial::uploadVirtualProgramPayload(
    std::vector<std::shared_ptr<VirtualProgramEntry>> instances)
{
    // collect data
    LambertianMaterialData *data = new LambertianMaterialData[instances.size()];
    for (size_t i = 0; i < instances.size(); i++)
    {
        auto mat = std::dynamic_pointer_cast<LambertianMaterial>(instances[i]);
        data[i].albedo = mat->albedo.getDeviceMipmap();
    }

    // set payload
    size_t payload_size = sizeof(LambertianMaterialData) * instances.size();
    this->sbt_data_payload.resize(payload_size);
    this->sbt_data_payload.upload(data, payload_size);

    delete[] data;
}

void LambertianMaterial::_buildFromConfig(const Json::Value &config)
{
    if (config["type"].asString().compare("lambertian") != 0)
    {
        std::cerr << "wrong config value is sent to LambertianMaterial::_buildFromConfig"
                  << std::endl;
        std::cerr << "got:" << config << std::endl;
        throw std::runtime_error("invalid parameter");
    }
    ColorTexture2D tex;
    ConfigHelpers::loadTexture2D(config["albedo"], tex);
    this->albedo.createFromTexture(tex);
}

CUdeviceptr LambertianMaterial::getPayloadDevicePtr()
{
    return LambertianMaterial::sbt_data_payload.d_pointer();
}

void LambertianMaterial::setProgram(std::shared_ptr<CudaProgram> prog)
{
    LambertianMaterial::program = prog;
}

std::shared_ptr<CudaProgram> LambertianMaterial::getProgram()
{
    return LambertianMaterial::program;
}

OptixProgramGroupOptions &LambertianMaterial::getProgramGroupOptions()
{
    return this->program_opt;
}

OptixProgramGroupDesc &LambertianMaterial::getProgramGroupDesc()
{
    this->program_desc.callables.moduleDC = this->cuda_module->optix_module;
    return this->program_desc;
}